import requests
import json
from flask import Flask, request, jsonify
from flask_cors import CORS
import time

app = Flask(__name__)
CORS(app)  # 启用 CORS，允许跨域请求

API_KEY = "6jPaXeWH2HbfXsfaJo76vAub"
SECRET_KEY = "31cO2arqq9zGtlGXOQ78OFSW4qpK19b3"

@app.route('/face', methods=['POST'])
def process_message():
    try:
        # 获取前端发送的 JSON 数据
        data = request.get_json()
        # 检查消息内容是否存在
        if not data or 'data' not in data:
            return jsonify({'error': 'Missing data'}), 400
        message = data['data']
        print(message)
        process_message=headMove(message)
        return process_message
    except Exception as e:
        # 错误处理
        return jsonify({'error': str(e)}), 500

def headMove(data):
    url = "https://aip.baidubce.com/rest/2.0/face/v3/faceverify?access_token=" + get_access_token()

    payload = json.dumps([
        {
            "image":data,
            "image_type": "BASE64"
        }
    ], ensure_ascii=False)
    headers = {
        'Content-Type': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))
    return response.text
    # print(response.text)
def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))

if __name__ == '__main__':
    app.run(debug=True, port=5006)